package com.meatball.core

import org.springframework.beans.BeansException
import org.springframework.beans.factory.config.BeanFactoryPostProcessor
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory
import org.springframework.stereotype.Component

/**
 * 解决不能注入问题
 * @author 张翔宇
 * @since 2023年3月30日
 * @version 1.0
 */
@Suppress("UNCHECKED_CAST")
@Component
class SpringUtils : BeanFactoryPostProcessor {
    @Throws(BeansException::class)
    override fun postProcessBeanFactory(beanFactory: ConfigurableListableBeanFactory) {
        Companion.beanFactory = beanFactory
    }

    companion object {
        /**
         * Spring应用上下文环境
         */
        var beanFactory: ConfigurableListableBeanFactory? = null
            private set

        @Throws(BeansException::class)
        fun <T> getBean(name: String?): T {
            return beanFactory!!.getBean(name!!) as T
        }

        @Throws(BeansException::class)
        fun <T> getBean(clz: Class<T>): T {
            return beanFactory!!.getBean(clz)
        }
    }
}
